//
//  NewsNeViewController.m
//  UI_A段项目_iDaily Watch
//
//  Created by lianglide on 14-10-13.
//  Copyright (c) 2014年 蓝欧科技. All rights reserved.
//

#import "NewsNeViewController.h"
#import "NewsSecondTableViewCell.h"
#import "NewsThirdTableViewCell.h"
#import "NewsPushViewController.h"
#import "BrandsViewController.h"
#import "AppDelegate.h"
#import "NewsModel.h"
#import "NewsGetData.h"
#import "UIButton+WebCache.h"
#import "MJRefresh.h"
#import "AFHTTPRequestOperationManager.h"
#import "DataBaseManager.h"
@interface NewsNeViewController ()

@end

@implementation NewsNeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //获取本地文件存储路径
       self.path =  NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
        _arrayFile1 = [[NSMutableArray alloc]init];
        _arrayFile2 = [[NSMutableArray alloc]init];
        _arrayFile3 = [[NSMutableArray alloc]init];
        _arrayFile4 = [[NSMutableArray alloc]init];
        
        
        
        NewsGetData * data = [[NewsGetData alloc]init];
      
        [data getDataFromBlock:^(NSMutableArray* dataSource) {
            self.dataSource = dataSource;
             [_table2 reloadData];
           
        }];
        _countx = 2;

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //self.navigationController.navigationBar.translucent = NO;
    
//    self.navigationController.navigationBar.translucent = NO;
//    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(80.0f, 0.0f, 160.0f, 44.0f)];
//    imageView.image = [UIImage imageNamed:@"TodayiDailyWatch.png"];
//    [self.navigationController.navigationBar addSubview:imageView];
//    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    
    UIButton *buttonA = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    buttonA.frame = CGRectMake(0, 0, 40, 30);
    buttonA.backgroundColor = [UIColor blackColor];
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc]initWithCustomView:buttonA];
    self.navigationItem.rightBarButtonItem = buttonItem;
    
    //self.tabBarController.tabBar.hidden = NO;
    
    _table2 = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, 320, 550 ) style:UITableViewStylePlain];
    _table2.delegate = self;
    _table2.dataSource = self;
    _table2.backgroundColor = [UIColor colorWithRed:48 /255.0 green:48 / 255.0 blue:48 / 255.0 alpha:1];
    _table2.backgroundColor = [UIColor blackColor];
    //去除分割线
    _table2.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    

    [self.view addSubview:_table2];
    [self switchToChangeAnimate];

    [self setupRefresh];

}
//隐藏tabBar
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

//    if (_dataSource.count == 0) {
//        
//        return 0;
//    }
    
     return _dataSource.count - 1;


}
#pragma mark -
#pragma mark cell样式
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
       
        NewsSecondTableViewCell *cell = [[NewsSecondTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
        cell.selectionStyle = NO;
        [cell.bbutton1 setBackgroundImageWithURL:[NSURL URLWithString:[_dataSource[indexPath.row]image2]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"1.png"]];
        cell.bbutton1.userInteractionEnabled = NO;
        cell.alable1.text = [_dataSource[0]title];
        cell.backgroundColor = [UIColor blackColor];
        return cell;
    }
    NewsThirdTableViewCell *cell = [[NewsThirdTableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
    
     cell.selectionStyle = NO;
       [cell.sbutton2 setBackgroundImageWithURL:[NSURL URLWithString:[_dataSource[indexPath.row ]image1]] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"1.png"]];
    cell.alable2.text = [_dataSource[indexPath.row]title];
    cell.sbutton2.userInteractionEnabled = NO;
    cell.imageTitle =[_dataSource[indexPath.row ]image1];
    //cell.backgroundColor = [UIColor colorWithRed:48 /255.0 green:48 / 255.0 blue:48 / 255.0 alpha:1];
    cell.backgroundColor = [UIColor clearColor];
    //_table2.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"背景5.jpeg"]];
    cell.alable3.text = [_dataSource[indexPath.row]pubdate1];
    [cell.button5 addTarget:self action:@selector(button5Action:) forControlEvents:UIControlEventTouchUpInside];
    cell.button5.tag = indexPath.row + 1000;
    
    
    cell.selectionStyle = NO;
        cell.alable4.text = [_dataSource[indexPath.row ]summary];
    
    return cell;
    
}
#pragma mark -
#pragma mark 文件本地化
-(void)button5Action:(UIButton *)button
{
    //创建数据库,每次只创建一次
//    if () {
//
//    }
    [DataBaseManager create];
    NewsModel *model = [[NewsModel alloc]init];

    model = [self.dataSource objectAtIndex:button.tag - 1000];
    NSLog(@"%@",model.title);
    NSLog(@"已收藏");
    _alertShow = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已收藏😊" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [_alertShow show];
    for (int i = 0; i < [DataBaseManager select].count; i ++) {
       
    if([model.title isEqualToString:[NSString stringWithFormat:@"%@",[[DataBaseManager select][i] title]]])
    {
        
        return;
        
        }
    }
    NSLog(@"%@pppppppp",model.title);
    [DataBaseManager insert:model];
    
//    NSString *filePath = [NSString stringWithFormat:@"%@/daily(title).txt",_path];
//    NSLog(@"%@", filePath);
//    self.arrayFile1 = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:filePath]];
//
//    NewsModel *model = [self.dataSource objectAtIndex:button.tag - 1000];
//    _model1 = [[NewsModel alloc]init];
//    
//    for (int i = 0; i < _arrayFile1.count; i ++) {
//        if ([[self.arrayFile1[i] title] isEqualToString:model.title]) {
//            
//            _alertShow = [[UIAlertView alloc]initWithTitle:@"提示" message:@"已收藏😊" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//            NSLog(@"😊😊😊😊😊😊😊😊%@",model.title);
//            
//            
//           
//        }
//         if(![[self.arrayFile1[i] title] isEqualToString:model.title] ){
//        
//    
//             _model1 = model;
//              NSLog(@"😢😢😢😢😢😢😢😢😢%@",model.title);
//            _alertShow = [[UIAlertView alloc]initWithTitle:@"提示" message:@"收藏成功😊" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
//        }
    
        
//}
//    NSLog(@"🐟🐟🐟🐟🐟🐟🐟🐟%@",_model1.title);
//    [self.arrayFile1 addObject:_model1];
//    NSLog(@"%@",self.arrayFile1);
//    [_alertShow show];
//    
//    [NSKeyedArchiver archiveRootObject:self.arrayFile1 toFile:filePath];
//    NSLog(@"🍎🍎🍎🍎🍎🍎🍎🍎%@",_arrayFile1);
//    NSLog(@"%@",filePath);


}
#pragma mark -
#pragma mark cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    if (indexPath.row == 0) {
        return Height * 160;
    }
    
    return Height * 190;
}
#pragma mark -
#pragma mark cell点击事件,传值
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    NewsPushViewController *vc = [[NewsPushViewController alloc]init];
    vc.getdata = _dataSource;
    vc.index = indexPath.row;
    [self.navigationController pushViewController:vc animated:YES];



}

#pragma mark-
#pragma mark 抽屉滑动手势方法
//支持滑动手势
- (void)switchValueChange {
   
    YRSideViewController *sideViewController=[[YRSideViewController alloc]init];
    [sideViewController setNeedSwipeShowMenu:YES];
}
//改变滑动动画
- (void)switchToChangeAnimate
{
    
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    YRSideViewController *sideViewController=[delegate sideViewController];

        [sideViewController setRootViewMoveBlock:^(UIView *rootView, CGRect orginFrame, CGFloat xoffset) {
            //使用简单的平移动画
            rootView.frame=CGRectMake(xoffset, orginFrame.origin.y, orginFrame.size.width, orginFrame.size.height);
        }];
  }

-(void)ITEMAction
{
    AppDelegate *delegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    YRSideViewController *sideViewController=[delegate sideViewController];
    [sideViewController showRightViewController:YES];

    
}

#pragma mark -
#pragma mark 刷新
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.table2 addHeaderWithTarget:self action:@selector(headerRereshing)];
   // [self.table2 headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.table2 addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.table2 footerEndRefreshing];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.table2.headerPullToRefreshText = @"下拉可以刷新了";
    self.table2.headerReleaseToRefreshText = @"松开马上刷新了";
    self.table2.headerRefreshingText = @"正在刷新中";
    
    self.table2.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.table2.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.table2.footerRefreshingText = @"加载中";
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.table2 reloadData];
        
        
        
        [_table2 reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.table2 headerEndRefreshing];
    });
}

- (void)footerRereshing
{
    //_dataSource = [[NSMutableArray alloc]init];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:[ NSString stringWithFormat:@"http://watch-cdn.idailywatch.com/api/list/magazine/zh-hans?page=%lu&ver=iphone&app_ver=9",(long)_countx] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSArray *arr = [NSArray array];
        arr = (NSArray *)responseObject;
        
        for (NSDictionary *dic in arr) {
            NewsModel  *mine = [[NewsModel alloc]init];
            mine.image1 = [dic objectForKey:@"cover_thumb"];
            mine.image2 = [dic objectForKey:@"cover_landscape_hd"];
            mine.title = [dic objectForKey:@"title"];
            mine.pubdate1 = [dic objectForKey:@"pubdate"];
            mine.summary = [dic objectForKey:@"summary"];
            mine.content = [dic objectForKey:@"content"];
            [_dataSource addObject:mine];
            
            
//            [self.table2 reloadData];
            
        }
        
        //self.dataBlock(_dataSource);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.table2 reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.table2 footerEndRefreshing];
        _countx += 1;
    });
    
    
    
    
}
#pragma mark -
#pragma mark cell将要出现时显示动画
- (void)tableView:(UITableView *)tableView willDisplayCell:(NewsSecondTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.frame = CGRectMake(320, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
    
        [UIView animateWithDuration:0.5 animations:^{
            cell.frame = CGRectMake(0, cell.frame.origin.y, cell.frame.size.width, cell.frame.size.height);
            
        }];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
